package com.genoworks.retriever.client;

import java.io.IOException;
import java.io.Writer;
import java.util.BitSet;
import java.util.TreeSet;

public class CharacterStrippingWriter extends Writer {
  private static final char[] DEFAULT_STRIP_CHARS = new char[ 32 ];
  private static final char DEFAULT_REPLACE_CHAR = ' ';
  static {
    for ( int i = 0; i < DEFAULT_STRIP_CHARS.length; i++ ) {
      DEFAULT_STRIP_CHARS[ i ] = (char) i;
    }
  }

  private Writer baseWriter = null;
  private BitSet stripChars = null;
  private char replaceChar = 0;

  public CharacterStrippingWriter( Writer writer ) {
    this( writer, DEFAULT_STRIP_CHARS, DEFAULT_REPLACE_CHAR );
  }

  public CharacterStrippingWriter( Writer writer, char[] charsToRemove,
      char charToReplace ) {

    //
    baseWriter = writer;
    replaceChar = charToReplace;

    //
    TreeSet<Character> sorter = new TreeSet<Character>();
    for ( char c : charsToRemove ) {
      sorter.add( c );
    }

    //
    stripChars = new BitSet( sorter.last().charValue() );
    for ( char c : sorter ) {
      stripChars.set( c );
    }
  }

  public void close() throws IOException {
    baseWriter.close();
  }

  public void flush() throws IOException {
    baseWriter.flush();
  }

  public void write( char[] buffer, int offset, int length ) throws IOException {
    for ( int i = 0; i < length; i++ ) {
      if ( buffer[ offset + i ] < stripChars.length() && stripChars.get( buffer[ offset + i ] ) ) {
        buffer[ offset + i ] = replaceChar;
      }
    }
    baseWriter.write( buffer, offset, length );
  }
}
